<template>
  <div class="miniapp-images-view">
    <div class="header">
      <h1>小程序图片管理</h1>
      <p>管理小程序中使用的背景图、图标、占位图等静态资源</p>
    </div>

    <!-- 操作栏 -->
    <el-card class="operation-card">
      <div class="operation-bar">
        <div class="filters">
          <el-select v-model="filters.page_name" placeholder="选择页面" clearable @change="loadImages">
            <el-option label="全部页面" value="" />
            <el-option label="发现页面" value="discover" />
            <el-option label="分类页面" value="category" />
            <el-option label="预约页面" value="appointment" />
            <el-option label="购物车页面" value="cart" />
            <el-option label="合作页面" value="cooperation" />
            <el-option label="个人中心" value="profile" />
            <el-option label="订单页面" value="order" />
            <el-option label="地址页面" value="address" />
            <el-option label="支付页面" value="payment" />
            <el-option label="商品详情" value="product" />
            <el-option label="首页" value="index" />
          </el-select>

          <el-select v-model="filters.image_type" placeholder="选择类型" clearable @change="loadImages">
            <el-option label="全部类型" value="" />
            <el-option label="背景图" value="background" />
            <el-option label="图标" value="icon" />
            <el-option label="横幅图" value="banner" />
            <el-option label="占位图" value="placeholder" />
            <el-option label="装饰图" value="decoration" />
          </el-select>

          <el-select v-model="filters.is_active" placeholder="选择状态" clearable @change="loadImages">
            <el-option label="全部状态" value="" />
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </div>

        <div class="actions">
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            添加图片配置
          </el-button>
          <el-button @click="loadImages">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 图片列表 -->
    <el-card class="images-card">
      <div v-loading="loading" class="images-container">
        <div v-if="images.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无图片配置" />
        </div>

        <div v-else class="images-grid">
          <div v-for="image in images" :key="image.id" class="image-item">
            <div class="image-preview">
              <img :src="getImageUrl(image.image_url)" :alt="image.image_name" @error="handleImageError" />
              <div class="image-overlay">
                <el-button size="small" type="primary" @click="previewImage(image)">
                  <el-icon><View /></el-icon>
                </el-button>
                <el-button size="small" @click="editImage(image)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button size="small" type="danger" @click="deleteImage(image)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>

            <div class="image-info">
              <div class="image-name">{{ image.image_name }}</div>
              <div class="image-key">{{ image.image_key }}</div>
              <div class="image-meta">
                <el-tag size="small" :type="getTypeTagType(image.image_type)">
                  {{ getTypeLabel(image.image_type) }}
                </el-tag>
                <el-tag size="small" :type="image.is_active ? 'success' : 'danger'">
                  {{ image.is_active ? '启用' : '禁用' }}
                </el-tag>
              </div>
              <div class="image-page">{{ getPageLabel(image.page_name) }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑图片配置' : '添加图片配置'"
      width="600px"
      @close="resetForm"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="图片键" prop="image_key">
          <el-select v-model="form.image_key" placeholder="请先选择所属页面" :disabled="isEdit || !form.page_name" filterable>
            <!-- 发现页面图片键 -->
            <template v-if="form.page_name === 'discover'">
              <el-option label="发现页背景图" value="discover_background" />
              <el-option label="发现页轮播图1" value="discover_banner_1" />
              <el-option label="发现页轮播图2" value="discover_banner_2" />
              <el-option label="发现页轮播图3" value="discover_banner_3" />
              <el-option label="品牌介绍背景图" value="discover_brand_bg" />
              <el-option label="特色服务背景图" value="discover_service_bg" />
              <el-option label="专业定制图标" value="service_icon_custom" />
              <el-option label="品质保证图标" value="service_icon_quality" />
              <el-option label="售后服务图标" value="service_icon_support" />
              <el-option label="线下体验图标" value="service_icon_experience" />
            </template>

            <!-- 分类页面图片键 -->
            <template v-if="form.page_name === 'category'">
              <el-option label="分类页背景图" value="category_background" />
              <el-option label="分类页装饰图" value="category_decoration" />
              <!-- 分类图标配置 -->
              <el-option label="戒圈戒指图标" value="category_icon_ring" />
              <el-option label="吊坠项链图标" value="category_icon_necklace" />
              <el-option label="耳饰图标" value="category_icon_earring" />
              <el-option label="手镯手链图标" value="category_icon_bracelet" />
              <el-option label="星钻图标" value="category_icon_diamond" />
            </template>

            <!-- 预约页面图片键 -->
            <template v-if="form.page_name === 'appointment'">
              <el-option label="预约页背景图" value="appointment_background" />
              <el-option label="预约介绍图" value="appointment_intro_image" />
              <el-option label="微信图标" value="appointment_wechat_icon" />
              <el-option label="电话图标" value="appointment_phone_icon" />
              <el-option label="服务优势背景图" value="appointment_advantage_bg" />
              <el-option label="流程箭头图标" value="appointment_arrow_down" />
              <el-option label="实物体验图标" value="advantage_icon_experience" />
              <el-option label="专业咨询图标" value="advantage_icon_consult" />
              <el-option label="个性定制图标" value="advantage_icon_custom" />
              <el-option label="品质保证图标" value="advantage_icon_quality" />
            </template>

            <!-- 购物车页面图片键 -->
            <template v-if="form.page_name === 'cart'">
              <el-option label="删除图标" value="cart_delete_icon" />
              <el-option label="购物车空状态图" value="cart_empty_image" />
            </template>

            <!-- 合作页面图片键 -->
            <template v-if="form.page_name === 'cooperation'">
              <el-option label="合作页背景图" value="cooperation_background" />
              <el-option label="合作招募横幅" value="cooperation_banner" />
              <el-option label="VIP介绍横幅" value="vip_intro_banner" />
              <el-option label="银卡会员图标" value="vip_silver_icon" />
              <el-option label="金卡会员图标" value="vip_gold_icon" />
              <el-option label="钻石会员图标" value="vip_diamond_icon" />
              <el-option label="VIP专属折扣图标" value="vip_benefit_discount_icon" />
              <el-option label="VIP优先服务图标" value="vip_benefit_priority_icon" />
              <el-option label="VIP免费保养图标" value="vip_benefit_maintenance_icon" />
              <el-option label="VIP专属客服图标" value="vip_benefit_service_icon" />
            </template>

            <!-- 个人中心图片键 -->
            <template v-if="form.page_name === 'profile'">
              <el-option label="默认头像" value="profile_default_avatar" />
            </template>

            <!-- 订单页面图片键 -->
            <template v-if="form.page_name === 'order'">
              <el-option label="订单空状态图" value="order_empty_image" />
            </template>

            <!-- 地址页面图片键 -->
            <template v-if="form.page_name === 'address'">
              <el-option label="地址空状态图" value="address_empty_image" />
            </template>

            <!-- 支付页面图片键 -->
            <template v-if="form.page_name === 'payment'">
              <el-option label="微信支付图标" value="payment_wechat_icon" />
              <el-option label="支付加载图标" value="payment_loading_icon" />
            </template>

            <!-- 商品详情页图片键 -->
            <template v-if="form.page_name === 'product'">
              <el-option label="商品默认图" value="product_default_image" />
            </template>

            <!-- 首页图片键 -->
            <template v-if="form.page_name === 'index'">
              <el-option label="首页Logo" value="index_logo" />
            </template>
          </el-select>
          <div class="form-tip">选择预定义的图片配置键，创建后不可修改</div>
        </el-form-item>

        <el-form-item label="图片名称" prop="image_name">
          <el-input v-model="form.image_name" placeholder="请输入图片名称，如: 发现页背景图" />
        </el-form-item>

        <el-form-item label="图片URL" prop="image_url">
          <div class="image-upload-container">
            <el-input v-model="form.image_url" placeholder="请输入图片URL或上传图片" />
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              name="image"
              accept="image/*"
            >
              <el-button type="primary">上传图片</el-button>
            </el-upload>
          </div>
          <div v-if="form.image_url" class="image-preview-small">
            <img :src="getImageUrl(form.image_url)" alt="预览" />
          </div>
        </el-form-item>

        <el-form-item label="图片类型" prop="image_type">
          <el-select v-model="form.image_type" placeholder="请选择图片类型">
            <el-option label="背景图" value="background" />
            <el-option label="图标" value="icon" />
            <el-option label="横幅图" value="banner" />
            <el-option label="占位图" value="placeholder" />
            <el-option label="装饰图" value="decoration" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属页面" prop="page_name">
          <el-select v-model="form.page_name" placeholder="请选择所属页面" @change="onPageNameChange">
            <el-option label="发现页面" value="discover" />
            <el-option label="分类页面" value="category" />
            <el-option label="预约页面" value="appointment" />
            <el-option label="购物车页面" value="cart" />
            <el-option label="合作页面" value="cooperation" />
            <el-option label="个人中心" value="profile" />
            <el-option label="订单页面" value="order" />
            <el-option label="地址页面" value="address" />
            <el-option label="支付页面" value="payment" />
            <el-option label="商品详情" value="product" />
            <el-option label="首页" value="index" />
          </el-select>
        </el-form-item>

        <el-form-item label="排序值" prop="sort_order">
          <el-input-number v-model="form.sort_order" :min="1" :max="999" />
          <div class="form-tip">数字越小越靠前</div>
        </el-form-item>

        <el-form-item label="状态">
          <el-switch v-model="form.is_active" active-text="启用" inactive-text="禁用" />
        </el-form-item>

        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入图片描述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="800px">
      <div class="image-preview-large">
        <img :src="previewImageUrl" :alt="previewImageName" />
      </div>
      <div class="preview-info">
        <p><strong>名称：</strong>{{ previewImageName }}</p>
        <p><strong>键值：</strong>{{ previewImageKey }}</p>
        <p><strong>URL：</strong>{{ previewImageUrl }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, View, Edit, Delete } from '@element-plus/icons-vue'
import { request } from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const previewVisible = ref(false)
const isEdit = ref(false)
const images = ref([])

// 筛选条件
const filters = reactive({
  page_name: '',
  image_type: '',
  is_active: ''
})

// 表单数据
const form = reactive({
  image_key: '',
  image_name: '',
  image_url: '',
  image_type: 'icon',
  page_name: '',
  sort_order: 99,
  is_active: true,
  description: ''
})

// 预览数据
const previewImageUrl = ref('')
const previewImageName = ref('')
const previewImageKey = ref('')

// 表单引用
const formRef = ref()

// 表单验证规则
const rules = {
  image_key: [
    { required: true, message: '请输入图片键', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '图片键只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  image_name: [
    { required: true, message: '请输入图片名称', trigger: 'blur' }
  ],
  image_url: [
    { required: true, message: '请输入图片URL', trigger: 'blur' }
  ],
  image_type: [
    { required: true, message: '请选择图片类型', trigger: 'change' }
  ],
  page_name: [
    { required: true, message: '请选择所属页面', trigger: 'change' }
  ]
}

// 上传配置
const uploadAction = ref(`${import.meta.env.VITE_API_BASE_URL}/miniapp-images/upload`)
const uploadHeaders = ref({
  'Authorization': `Bearer ${authStore.token}`
})

// 加载图片列表
const loadImages = async () => {
  loading.value = true
  try {
    const params = {}
    if (filters.page_name) params.page_name = filters.page_name
    if (filters.image_type) params.image_type = filters.image_type

    // 确保布尔值正确传递
    if (filters.is_active !== '') {
      // 将布尔值转换为字符串，确保后端能正确解析
      params.is_active = String(filters.is_active)
    }

    const response = await request.get('/miniapp-images', { params })
    images.value = response.data
  } catch (error) {
    ElMessage.error('获取图片列表失败')
  } finally {
    loading.value = false
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑图片
const editImage = (image: any) => {
  isEdit.value = true
  // 确保正确复制数据，特别是布尔值
  Object.assign(form, {
    ...image,
    is_active: Boolean(image.is_active) // 确保是布尔值
  })
  console.log('编辑图片数据:', form) // 调试日志
  dialogVisible.value = true
}

// 删除图片
const deleteImage = async (image: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除图片配置"${image.image_name}"吗？`, '确认删除')

    await request.delete(`/miniapp-images/${image.id}`)
    ElMessage.success('删除成功')
    loadImages()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 预览图片
const previewImage = (image: any) => {
  previewImageUrl.value = getImageUrl(image.image_url)
  previewImageName.value = image.image_name
  previewImageKey.value = image.image_key
  previewVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 确保提交的数据中布尔值类型正确
    const submitData = {
      ...form,
      is_active: Boolean(form.is_active) // 确保是布尔值
    }

    console.log('提交数据:', submitData) // 调试日志
    console.log('是否编辑模式:', isEdit.value) // 调试日志

    if (isEdit.value) {
      // 编辑模式下，确保包含 id
      const imageId = (form as any).id
      console.log('更新图片ID:', imageId) // 调试日志
      await request.put(`/miniapp-images/${imageId}`, submitData)
      ElMessage.success('更新成功')
    } else {
      await request.post('/miniapp-images', submitData)
      ElMessage.success('创建成功')
    }

    dialogVisible.value = false
    loadImages()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    console.error('提交表单失败:', error)
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    image_key: '',
    image_name: '',
    image_url: '',
    image_type: 'icon',
    page_name: '',
    sort_order: 99,
    is_active: true,
    description: ''
  })
}

// 上传成功处理
const handleUploadSuccess = (response: any) => {
  if (response.success) {
    form.image_url = response.data.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

// 上传失败处理
const handleUploadError = () => {
  ElMessage.error('图片上传失败')
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 获取图片完整URL
const getImageUrl = (url: string) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `${import.meta.env.VITE_API_BASE_URL}${url}`
}

// 图片加载错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/src/assets/image-error.png' // 需要添加一个错误占位图
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap = {
    background: 'primary',
    icon: 'success',
    banner: 'warning',
    placeholder: 'info',
    decoration: 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取类型标签文本
const getTypeLabel = (type: string) => {
  const typeMap = {
    background: '背景图',
    icon: '图标',
    banner: '横幅图',
    placeholder: '占位图',
    decoration: '装饰图'
  }
  return typeMap[type] || type
}

// 获取页面标签文本
const getPageLabel = (pageName: string) => {
  const pageMap = {
    discover: '发现页面',
    category: '分类页面',
    appointment: '预约页面',
    cart: '购物车页面',
    cooperation: '合作页面',
    profile: '个人中心',
    order: '订单页面',
    address: '地址页面',
    payment: '支付页面',
    product: '商品详情',
    index: '首页'
  }
  return pageMap[pageName] || pageName
}

// 页面名称变化时清空图片键选择
const onPageNameChange = () => {
  form.image_key = ''
}

// 组件挂载时加载数据
onMounted(() => {
  loadImages()
})
</script>

<style scoped>
.miniapp-images-view {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.operation-card {
  margin-bottom: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filters {
  display: flex;
  gap: 12px;
}

.filters .el-select {
  width: 150px;
}

.actions {
  display: flex;
  gap: 12px;
}

.images-card {
  min-height: 400px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.image-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.image-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.image-preview {
  position: relative;
  height: 160px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.image-preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview:hover .image-overlay {
  opacity: 1;
}

.image-info {
  padding: 12px;
}

.image-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  font-size: 14px;
}

.image-key {
  font-size: 12px;
  color: #909399;
  font-family: monospace;
  margin-bottom: 8px;
}

.image-meta {
  display: flex;
  gap: 6px;
  margin-bottom: 6px;
}

.image-page {
  font-size: 12px;
  color: #606266;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.image-upload-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.image-upload-container .el-input {
  flex: 1;
}

.image-preview-small {
  margin-top: 8px;
}

.image-preview-small img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.image-preview-large {
  text-align: center;
  margin-bottom: 20px;
}

.image-preview-large img {
  max-width: 100%;
  max-height: 400px;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-info {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 6px;
}

.preview-info p {
  margin: 0 0 8px 0;
  font-size: 14px;
  line-height: 1.5;
}

.preview-info p:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  text-align: right;
}
</style>
